package com.it.a11test5;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

public class MyRunable implements Runnable {
    //利用构造方法传递 Socket对象
    Socket s;
    public MyRunable(Socket s) {
        this.s = s;
    }
    public void run() {
        try {
            //接收客户端上传的文件，上传完毕之后给出反馈.
            BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
            String name = UUID.randomUUID().toString().replace("-", "");
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\java\\basic-code\\mysockstnet\\severdir\\"+name+".jpeg"));
            byte[] buf = new byte[1024];
            int len;
            while ((len = bis.read(buf)) != -1) {
                bos.write(buf, 0, len);
            }
            //回写数据
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            bw.write("上传成功");
            bw.newLine();
            bw.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //释放数据
            if(s != null) {
                try {
                    s.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
